// JavaScript Document
var map;
var markersArray = [];
$(document).ready(function(){
    var latlng = new google.maps.LatLng(43.068368, -87.90);
    var myOptions = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false 
    };
    map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
        
    $("#login-form").submit(function() {
	var password = $("#login-password").val();
	var email = $("#login-email").val();
	$.post("actions/login.php", {"Email": email, "Password": password},
		function(response){
			var resp = $.parseJSON(response);
			if (resp.Error != undefined){
				alert("FAIL");
			}else if(resp.Email != undefined){
				$("div#login-dropdown").slideUp();
				$("div#loginRegister").hide();
				$("span#loginInfo").html("Hello " + resp.Email + "!");
				$("div#login-info-dropdown").show();

			}
		});
    	return false;
    }); 
    $("#register-form").submit(function() {

	var password = $("#register-password").val();
	var name = $("#register-name").val();
	var lname = $("#register-lname").val();
	var email = $("#register-email").val();
	$.post("actions/register.php", {"Email": email, "Password": password, "FirstName": name, "LastName": lname},
		function(response){
			var resp = $.parseJSON(response);
			if (resp.Error != undefined){
				alert("Invalid Credentials");
			}else if(resp.Email != undefined){
				$("div#register-dropdown").slideUp();
				$("div#loginRegister").hide();
				$("span#loginInfo").html("Hello " + resp.Email + "!");
				$("div#login-info-dropdown").show();
			}
		});
    	return false;
    });

	$("#submitFrame").load(function()
	{
		var response = $("#submitFrame").contents().text();
		alert(response);
		var json = $.parseJSON(response);
		
		//clear overlays
		if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
    }
    
    markersArray = [];
		
		getMarkers();
	});
    
    google.maps.event.addListener(map, 'tilesloaded', function(){
      getMarkers();
    });
    
    google.maps.event.addListener(map, 'click', function(event){
      $("#add-spot-x").val(event.latLng.lng());
      $("#add-spot-y").val(event.latLng.lat());
    });
});

function vote(value, id){
	$.post("actions/voteSpot.php", {"SpotID": id, "Vote": value},
		       function(resp){
			       
			       var voteData = $.parseJSON(resp);
			       if(voteData.Error != undefined){

			       alert(voteData.UpVotes);
			       $("#votes").html("<div id=\"votes\">UpVotes: "+voteData.UpVotes+"<br/> DownVotes: "+voteData.DownVotes+"</div>");
			       }
		       });
}

function getMarkers(){
  var data = [
      {
        id: 1,
        imageurl: "../images/testOverlay.jpg" , 
        lat:43.068368,
        lng: -87.90,
	      title: "Tester!!"	
      }
  ];
  
  $.post("actions/getSpots.php", 
	{"swLat": map.getBounds().getSouthWest().lat(), "swLon": map.getBounds().getSouthWest().lng(), "neLat": map.getBounds().getNorthEast().lat(), "neLon": map.getBounds().getNorthEast().lng()}, 
	function(response){
		data = $.parseJSON(response);
		for(i in data){
			var spot = data[i];
		     	addSpot(spot);
		 }
  	});

}

function addSpot(spot){
 var window = new google.maps.InfoWindow();
     var marker = new google.maps.Marker({
        position: new google.maps.LatLng(spot.X, spot.Y),
        title: spot.Title,
     });
     if(spot.UpVotes < 5){
        marker.icon = "images/ptr_green.png";
     }else if(spot.UpVotes < 10){
        marker.icon = "images/ptr_yellow.png";
     }else{
        marker.icon = "images/ptr_red.png";
     }
     marker.setMap(map);
     markersArray.push(marker);
     var htmlString = "<div id=\"title\"> "+ spot.Title + "</div><br /> <div id=\"image\"><img src = \"images/" + spot.Image +"\" class='imageThumb\'></img></div>";
           
     window.setContent(htmlString);
     
     google.maps.event.addListener(marker, 'mouseover',
        function() {
           window.open(map, marker);
        }
    );
    
    google.maps.event.addListener(marker, 'mouseout',
        function() {
           window.close();
        }
    );
    
    google.maps.event.addListener(marker, 'click',
        
        function() {
           window.close();
		      $( "#spotDialog" ).dialog({
		       position: 'center',
			     modal: true,
			     resizable: true,
			     //height: 700,
				 //width: 700,
			     height: 900,
				 width: "90%",
			       open: function() {
				        getSpot(spot.ID);
					    $("#upVote").click(function(){
						    vote(1, spot.ID);
					    });
					    $("#downVote").click(function(){
						    vote(0, spot.ID);
					    });
			       },                                  
			  });
		});
		
}

function getSpot(id){
	var retVal;
	$("#spotID").val(id);
	$.post("actions/getSpot.php",
		{"ID": id},
		function(response){
			var spotData = $.parseJSON(response);
			getMessages(spotData[0]);
			
			return $.parseJSON(response);

		});
}
function getMessages(spotData){
	var retVal;
	$("#spotDialog #title").html("");
	$("#spotDialog #message").html("");
	$("#spotDialog #image").html("");
	$("#spotDialog #title").html("<h3>"+spotData.Title+"</h3>");
	$("#spotDialog #image").html("<img src=\"images/"+spotData.Image+"\"  class=\"imagePreview\"/>");
	$("#spotDialog #image").append("<div id=\"votes\">UpVotes: "+spotData.UpVotes+"<br/> DownVotes: "+spotData.DownVotes+"</div>");

	$.post("actions/getSpotMessages.php",
		{"SpotID": spotData.ID},
		function(response){
			var messageData = $.parseJSON(response);

			for(i in messageData){
				var message = messageData[i];
				
				$("#spotDialog #messages").append("<li style=\"message\"><strong>" + message.FirstName + " " + message.LastName + "</strong>: "+message.Message+"</li>");
			}
		});
}

function addMessage()
{
	var spotID = $("#spotID").val();
	var message = $("#spotMessage").val();
	$("#spotMessage").val("");
	
	$.post("actions/addMessage.php",
		{"SpotID": spotID, "Message": message},
		function(response)
		{
			var json = $.parseJSON(response);
			if(json.Error != undefined)
			{
				alert(json.Error);
			}
			else
			{
				$("#spotDialog #messages").prepend("<li style=\"message\"><strong>" + json.FirstName + " " + json.LastName + "</strong>: "+json.Message+"</li>");
			}
		}
	);
}

function hideAll()
{
	$("div#login-dropdown").hide();
	$("div#register-dropdown").hide();
	$("div#submit-spot-dropdown").hide();
}
function showLogin(){
	hideAll();
	$("div#login-dropdown").slideDown();
}
function showRegister(){
	hideAll();
	$("div#register-dropdown").slideDown();
}
function showSubmitSpot(){
	hideAll();
	$("div#submit-spot-dropdown").slideDown();
}
